package com.augurit.common.system.web.org;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;

import com.augurit.common.base.action.ExtCrudActionSupport;
import com.augurit.common.system.service.org.IAcFunctionService;
import com.augurit.common.system.service.org.IAcMenuService;
import com.augurit.common.system.service.org.IAcRoleService;
import com.augurit.common.system.service.org.IAcUserShortcutService;
import com.augurit.common.system.service.org.IOmOrgService;
import com.augurit.common.system.service.org.IOmUserService;
import com.augurit.common.system.util.WebContextUtils;
import com.augurit.common.system.web.org.form.OmOrgForm;
import com.augurit.common.system.web.org.form.OmUserForm;
import com.augurit.common.util.ExtUtils;
import com.augurit.common.util.lang.ArrayUtils;
import com.augurit.gzcgwsp.sendNotice.service.IUserForFxService;

/**
 * 用户管理Action类
 */
@SuppressWarnings("serial")
public class OmUserAction extends ExtCrudActionSupport<OmUserForm> {

	// Service 引用
	@Autowired
	private IOmUserService omUserService;
	
	@Autowired
	private IAcRoleService acRoleService;
	
	@Autowired
	private IAcFunctionService acFunctionService;
	
	@Autowired
	private IAcMenuService acMenuService;
	
	@Autowired
	private IAcUserShortcutService acUserShortcutService;
	
	@Autowired
	private IOmOrgService omOrgService;
	
	@Autowired
	private IUserForFxService userForFxService;

	
	// 基本属性
	private Page<OmUserForm> page = new Page<OmUserForm>(15);
	private OmUserForm form;

	private Long menuId;
	
	private Long funcId;
	private Long[] funcIds;
	
	private Long userId;
	private Long[] userIds;

	private Long orgId;
	private Long groupId;
	private Long posId;
	
	private Long roleId;
	private Long[] roleIds;

	
	/**
	 * 查询用户记录
	 */
	public String list() throws Exception {
		ExtUtils.initPageFromExtGridParam(this.getRequest(), page);
		omUserService.searchUser(this.getLoginUserId(), form, page,
				WebContextUtils.getSysCodeBuffer(this.getApplication()));
		this.extRenderGridJson(page);
		return null;
	}
	
	/**
	 * 判断是否为系统管理员
	 */
	public String isSystemAdmin()throws Exception{
		if(omUserService.isSystemAdmin(this.getLoginUserId()))
			this.renderText("{canManager:true}");
		else
			this.renderText("{canManager:false}");
		return null;
	}
	
	/**
	 * 判断是用户是否有为机构管理员或者系统管理员
	 */
	public String isAdminUser()throws Exception{
		List<OmOrgForm> list = omOrgService.getCanManageOrgs(this.getLoginUserId());
		if(list != null && list.size() > 0)
			this.renderText("{canManager:true}");
		else
			this.renderText("{canManager:false}");
		return null;
	}


	/**
	 * 获取不隶属于指定机构的用户列表
	 * @param orgId 指定机构ID
	 */
	public String getUsersNotInOrg() throws Exception {
		ExtUtils.initPageFromExtGridParam(this.getRequest(), page);
		omUserService.getUsersNotInOrg(orgId, form, page);
		this.extRenderGridJson(page);
		return null;
	}
	
	/**
	 * 获取机构下所有的用户（包括它的所有子机构）
	 * @return
	 * @throws Exception
	 */
	public String getUsersInOrgButNotInGroup() throws Exception {
		ExtUtils.initPageFromExtGridParam(this.getRequest(), page);
		omUserService.getUsersInOrgButNotInGroup(orgId, groupId, form, page);
		this.extRenderGridJson(page);
		return null;
	}
	
	/**
	 * 获取机构下不拥有指定岗位的所有用户，包括子机构下的用户
	 * @return
	 * @throws Exception
	 */
	public String getUsersNotHavePos() throws Exception {
		ExtUtils.initPageFromExtGridParam(this.getRequest(), page);
		omUserService.getUsersNotHavePos(orgId, posId, form, page);
		this.extRenderGridJson(page);
		return null;
	}

	/**
	 * 根据机构id查询 user
	 */
	public String getUserByOrgId() throws Exception {
		omUserService.getUsers(orgId, page);
		this.extRenderGridJson(page);
		return null;
	}
	
	/**
	 * 根据工作组id查询 user
	 */
	public String getUserByGroupId() throws Exception {
		ExtUtils.initPageFromExtGridParam(this.getRequest(), page);
		omUserService.getUsersByGroup(groupId, page);
		this.extRenderGridJson(page);
		return null;
	}

	/**
	 * 根据岗位id查询关联user
	 */
	public String getUserByPosId() throws Exception {
		omUserService.getUsersByPosId(posId, page);
		this.extRenderGridJson(page);
		return null;
	}

	/**
	 * 新增或编辑用户页面
	 */
	@Override
	public String input() throws Exception {
//		this.renderOmUserFormJson(form);
		this.extRenderFormJson(form);
		return null;
	}

	/**
	 * 删除一个或多个用户
	 */
	@Override
	public String delete() throws Exception {
		if (userIds != null && userIds.length > 0) {
			for (Long userId : userIds)
				this.omUserService.deleteUserCascade(userId);
		}
		this.extRenderSuccess();
		return null;
	}
	
	/**
	 * 删除用户与机构的关联，不删除用户本身
	 * @return
	 * @throws Exception
	 */
	public String deleteFromOrg() throws Exception {
		if(userIds != null && userIds.length > 0 && orgId != null){
			for(Long userId:userIds){
				omUserService.deleteUserFromOrg(userId, orgId,true);
			}
		}
		this.extRenderSuccess();
		return null;
	}
	
	/**
	 * 删除用户与岗位的关联，不删除用户本身
	 * @return
	 * @throws Exception
	 */
	public String deleteFromPos() throws Exception {
		if(userIds != null && userIds.length > 0 && posId != null){
			for(Long userId:userIds)
				omUserService.deleteUserFromPos(userId, posId);
		}
		this.extRenderSuccess();
		return null;
	}
	
	/**
	 * 删除用户与岗位的关联，不删除用户本身
	 * @return
	 * @throws Exception
	 */
	public String deleteFromGroup() throws Exception {
		if(userIds != null && userIds.length > 0 && groupId != null){
			for(Long userId:userIds)
				omUserService.deleteUserFromGroup(userId, groupId);
		}
		this.extRenderSuccess();
		return null;
	}

	/**
	 * 获取指定用户的已授权角色
	 */
//	public String getRolesByUserId() throws Exception {
//		Page<AcRoleForm> page = null;
//		if (userId != null) {
//			page = new Page<AcRoleForm>(PageContant.PAGE_SIZE_DEFAULT); // 默认每页10条记录
//			page = acRoleService.getRolePageByUserId(userId, page);
//		}
//		this.extRenderGridJson(page);
//		return null;
//	}
 

	/**
	 * 设置特别开通的功能
	 */
	public String setOpenedFunsForUser() throws Exception {
		if (userId != null && funcIds != null && funcIds.length > 0) {
			acFunctionService.setOpenedFunsForUser(funcIds, userId);
			this.extRenderSuccess();
		}
		return null;
	}

	/**
	 * 为多个用户设置一个特别开通的功能
	 */
	public String setOpenedFuncForUsers() throws Exception {
		if (funcId != null && userIds != null && userIds.length > 0) {
			acFunctionService.setOpenedFunForUsers(userIds, funcId);
			this.extRenderSuccess();
		}
		return null;
	}

	/**
	 * 设置特别禁止的功能
	 */
	public String setForbiddenFunsForUser() throws Exception {
		if (userId != null && funcIds != null && funcIds.length > 0) {
			acFunctionService.setForbiddenFunsForUser(funcIds, userId);
			this.extRenderSuccess();
		}
		return null;
	}

	/**
	 * 为某一批用户设置某项特别禁止功能
	 * @param userIds 用户id数组
	 * @param funcId 功能id
	 */
	public void setForbiddenFunForUsers() throws Exception {
		if (funcId != null && userIds != null && userIds.length > 0) {
			acFunctionService.setForbiddenFunForUsers(userIds, funcId);
		}
	}
	
	/**
	 * 获取拥有指定菜单的权限但是没有把这个菜单设置为快捷菜单的用户
	 * @param shortcutId 快捷菜单id 
	 */
	public String getUsersNotOwnedShortcut() throws Exception{
		ExtUtils.initPageFromExtGridParam(this.getRequest(), page);
		Long funcId = acMenuService.getRelatedFuncIdByMenuId(menuId);
		Long[] userIdsOwnedMenu = acRoleService.getUserIdsByFuncId(funcId);
		Long[] userIdsOwendShortcut = acUserShortcutService.getUserIdsOwnedShortcuts(menuId);
		Long[] userIds = ArrayUtils.calDifference(userIdsOwnedMenu, userIdsOwendShortcut);
			
		omUserService.getUsersInUserIds(page, form, userIds);
		this.extRenderGridJson(page);
		return null;
	}
	
	/**
	 * 获取拥有指定快捷菜单的用户
	 * @param shortcutId 快捷菜单id
	 */
	public String getUsersOfShortcut() throws Exception{
		ExtUtils.initPageFromExtGridParam(this.getRequest(), page);
		Long[] userIds = acUserShortcutService.getUserIdsOwnedShortcuts(menuId);
		omUserService.getUsersInUserIds(page, form, userIds);
		this.extRenderGridJson(page);
		return null;
	}

	/**
	 * 获取指定用户的继承角色
	 * @param userIds 用于接收增加已有机构用户的ID集合
	 */
	public String associateUserToOrg() throws Exception {
		if (userIds != null && userIds.length > 0)
			for (Long userId : userIds) 
				omUserService.associateUserToOrg(userId, orgId);
		
		this.extRenderSuccess();
		return null;
	}

	/**
	 * 保存用户信息
	 */
	@Override
	public String save() throws Exception {
		//MD5加密密码
		form.setPassword(org.hsqldb.lib.MD5.encodeString(form.getPassword(), "UTF-8"));
		//新增用户
		if (form.getUserId() == null) {
			//在机构下增加
			if(orgId != null){
				//根节点下新增用户
				if(orgId == -1){
					this.omUserService.save(form);
				}
				//普通机构下新增用户
				else{
					omUserService.addUserToOrg(form, orgId);
				}
				
				
				
				//新增用户同步
				userForFxService.saveUser(form, orgId, posId);
			}
			//在机构岗位下增加
			else if(posId != null){
				omUserService.addUserToOrgPos(form, posId);
			}
		} 
		//修改用户
		else{
			omUserService.save(form);
			//修改用户同步
			userForFxService.updateUser(form, orgId, posId);
		}
		
		this.extRenderSuccess();
		return null;
	}

	/**
	 * 将Form对象转换为Ext的FormPanel组件所需的JSON字符串
	 */
//	public static void renderOmUserFormJson(final BaseForm form) {
//		List<BaseForm> list = new ArrayList();
//		list.add(form);
//
//		JsonConfig jsonConfig = configJson();
//		String jsonString = JSONArray.fromObject(list, jsonConfig).toString();
//
//		StringBuffer sb = new StringBuffer("{success:true,result:");
//		sb.append(jsonString);
//		sb.append("}");
//
//		renderJson(sb.toString());
//	}

	/**
	 * 获取与指定角色关联的用户
	 * @author 王剑文
	 */
	public String getUsersByRole() throws Exception {
		ExtUtils.initPageFromExtGridParam(this.getRequest(), page);
		acRoleService.getUsersByDirectRoleId(page, roleId);
		this.extRenderGridJson(page);
		return null;
	}

	/**
	 * 获取与指定角色不关联的用户
	 * @author 王剑文
	 */
	public String getUsersNotAssociateRole() throws Exception {
		ExtUtils.initPageFromExtGridParam(this.getRequest(), page);
		acRoleService.getUsersNotAssociateRole(page, roleId, form);
		this.extRenderGridJson(page);
		return null;
	}

	/**
	 * 获取具有指定功能的所有用户
	 * @author 王剑文
	 */
	public String getUsersByFuncId() throws Exception {
		ExtUtils.initPageFromExtGridParam(this.getRequest(), page);
		Long[] userIds = acRoleService.getUserIdsByFuncId(funcId);
		omUserService.getUsersInUserIds(page, form, userIds);
		this.extRenderGridJson(page);
		return null;
	}

	/**
	 * 获取不具有某项功能的所有用户
	 * @author 王剑文
	 */
	public String getUsersNotAssociateFunction() throws Exception {
		ExtUtils.initPageFromExtGridParam(this.getRequest(), page);
		Long[] userIds = acRoleService.getUserIdsByFuncId(funcId);
		omUserService.getUsersNotInUserIds(page, form, userIds);
		this.extRenderGridJson(page);
		return null;
	}
	
	public OmUserForm getModel() {
		return form;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (userId != null)
			form = omUserService.get(userId);
		else
			form = new OmUserForm();
	}
	
	
	// 属性getter和setter方法
	public Page<OmUserForm> getUserPage() {
		return page;
	}

	public Long getUserId() {
		return userId;
	}

	public void setUserPage(Page<OmUserForm> page) {
		this.page = page;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public Page<OmUserForm> getPage() {
		return page;
	}

	public Long getOrgId() {
		return orgId;
	}

	public void setPage(Page<OmUserForm> page) {
		this.page = page;
	}

	public void setOrgId(Long orgId) {
		this.orgId = orgId;
	}

	public OmUserForm getOmUserForm() {
		return form;
	}

	public Long getPosId() {
		return posId;
	}

	public void setOmUserForm(OmUserForm omUserForm) {
		this.form = omUserForm;
	}

	public void setPosId(Long posId) {
		this.posId = posId;
	}

	public Long[] getUserIds() {
		return userIds;
	}

	public void setUserIds(Long[] userIds) {
		this.userIds = userIds;
	}

	public Long[] getRoleIds() {
		return roleIds;
	}

	public void setRoleIds(Long[] roleIds) {
		this.roleIds = roleIds;
	}

	public Long getRoleId() {
		return roleId;
	}

	public void setRoleId(Long roleId) {
		this.roleId = roleId;
	}

	public Long[] getFuncIds() {
		return funcIds;
	}

	public void setFuncIds(Long[] funcIds) {
		this.funcIds = funcIds;
	}

	public Long getFuncId() {
		return funcId;
	}

	public void setFuncId(Long funcId) {
		this.funcId = funcId;
	}

	public Long getMenuId() {
		return menuId;
	}

	public void setMenuId(Long menuId) {
		this.menuId = menuId;
	}

	public Long getGroupId() {
		return groupId;
	}

	public void setGroupId(Long groupId) {
		this.groupId = groupId;
	}
}
